<template>
	<div class="nurse_table">
		<div class="title">
			<p>康恒医院护士信息表</p>
		</div>
		<div class="filter-container">
			<el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="护士姓名"
				v-model="searchName">
			</el-input>
			<el-button class="filter-item" type="primary" icon="search" @click="handelSearch">搜索</el-button>
			<el-button type="primary" icon="" @click="getAll">显示全部</el-button>
			<el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
		</div>

		<el-table ref="multipleTable" :data="table" border tooltip-effect="dark" style="width: 100%">
			<el-table-column prop="id" label="编号" width="120"></el-table-column>
			<el-table-column prop="name" label="姓名" width="120"></el-table-column>
			<el-table-column prop="address" label="地址" show-overflow-tooltip></el-table-column>
			<el-table-column prop="sex" label="性别" show-overflow-tooltip width="70"></el-table-column>
			<el-table-column prop="age" label="年龄" sortable align="center" show-overflow-tooltip
				width="100"></el-table-column>
			<el-table-column prop="position" label="职称" show-overflow-tooltip width="100"></el-table-column>
			<el-table-column prop="department" label="科室" show-overflow-tooltip></el-table-column>
			<el-table-column prop="education" label="学历" show-overflow-tooltip></el-table-column>
			<el-table-column prop="profession" label="专业" show-overflow-tooltip></el-table-column>
			<el-table-column prop="date" label="入职时间" sortable show-overflow-tooltip></el-table-column>
			<el-table-column fixed="right" prop="operate" label="操作" width="150">
				<template scope="scope">
					<el-button size="small" type="primary" @click="handleEdit(scope.$index)">编辑</el-button>
					<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">失效</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 编辑信息的表单 -->
		<el-dialog title="修改个人信息" :visible.sync="dialogFormEditVisible">
			<el-form class="small-space" :model="form" label-position="left" label-width="70px"
				style='width: 400px; margin-left:10px;'>
				<el-form-item label="姓名" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.name"></el-input>
				</el-form-item>
				<el-form-item label="地址" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.address"></el-input>
				</el-form-item>
				<el-form-item label="年龄" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.age"></el-input>
				</el-form-item>
				<el-form-item label="职称" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.position"></el-input>
				</el-form-item>
				<el-form-item label="专业" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.profession"></el-input>
				</el-form-item>
				<el-form-item label="科室" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.department"></el-input>
				</el-form-item>
				<el-form-item label="学历" :label-width="formLabelWidth">
					<el-input v-model="tableEdit.education"></el-input>
				</el-form-item>
				<el-form-item label="性别" :label-width="formLabelWidth">
					<el-radio class="radio" v-model="tableEdit.sex" label="男">男</el-radio>
					<el-radio class="radio" v-model="tableEdit.sex" label="女">女</el-radio>
				</el-form-item>
				<el-form-item label="入职时间">
					<el-col :span="11">
						<el-form-item prop="date">
							<el-date-picker type="date" placeholder="选择日期" v-model="tableEdit.date"></el-date-picker>
						</el-form-item>
					</el-col>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormEditVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleEditSubmit">确 定</el-button>
			</div>
		</el-dialog>

		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="pageNum" :page-sizes="[10,20,30,40]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="totalNum">
			</el-pagination>
		</div>

	</div>
</template>

<script type="text/ecmascript-6">
	import Vue from 'vue';
	import {
		debounce
	} from 'lodash';
	import {
		api
	} from '../../../global/api.js';
	export default {
		data() {
			return {
				table: [],//护士信息
				tableEdit: [],//编辑护士信息
				Index: '',
				searchName: '',
				searchDepartment: '',
				totalNum: 0,
				pageNum: 1,
				pageSize: 10,
				dialogFormEditVisible: false,
				// 表单input的限制长度
				formLabelWidth: '60px',
				form: {
					name: '',
					address: '',
					age: '',
					position: '',
					profession: '',
					department: '',
					education: '',
					sex: '',
					date: ''
				},
				cache: {},
				processor: ''
			};
		},
		methods: {
			// 获取护士
			init() {
				let that = this;
				let cacheKey = `${that.pageNum}-${that.pageSize}-${that.searchName}`;
				if (that.cache[cacheKey]) {
					that.table = that.cache[cacheKey].data;
					that.totalNum = that.cache[cacheKey].count;
					return;
				}
				let API = "http://localhost:8088/getAllNurse";
				this.$http.get(API, {
					params: {
						"pageNum": that.pageNum,
						"pageSize": that.pageSize,
						"search": that.searchName
					}
				}).then((response) => {
					for (var i = 0; i < response.body.data.length; i++) {
						if (response.body.data[i].sex == 1) {
							response.body.data[i].sex = "男";
						} else {
							response.body.data[i].sex = "女";
						}
						const dateString = response.body.data[i].date;
						const date = new Date(dateString);

						const year = date.getFullYear();
						const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
						const day = String(date.getDate()).padStart(2, '0');

						const formattedDate = `${year}-${month}-${day}`;

						response.body.data[i].date = formattedDate;
					}
					that.table = response.body.data;
					that.totalNum = response.body.count;
					that.cache[cacheKey] = {
						data: response.body.data,
						count: response.body.count
					}; // 缓存数据
					console.log(response);
				}, response => {
					this.$message({
						message: '数据请求失败',
						type: 'error'
					});
				});
			},
			// 编辑
			handleEdit(index) {
				let that = this;
				this.dialogFormEditVisible = true;
				that.Index = index; // 存放当前行的序号
				that.tableEdit = {
					...that.table[index]
				}; // 获取当前行的数据的副本
			},
			// 编辑表单的提交
			handleEditSubmit() {
				let that = this;
				if (that.tableEdit.sex == "男") {
					that.tableEdit.sex = 1;
				} else {
					that.tableEdit.sex = 2;
				}

				// 判断此日期是否需要更改
				let date = false;
				// 定义正则表达式来匹配日期格式
				const dateRegex = /^\w{3} \w{3} \d{2} \d{4} \d{2}:\d{2}:\d{2} GMT[+-]\d{4} \(.*\)$/;
				const dateString = that.tableEdit.date;
				// 使用正则表达式验证格式
				if (dateRegex.test(dateString)) {
					if (!isNaN(that.tableEdit.date.getTime())) {
						date = true; // 更改为此日期需要更改
						console.log("日期格式正确且有效");
					} else {
						console.log("日期格式正确但无效");
					}
				} else {
					console.log("日期格式不正确");
				}

				if (date) {
					// 转换时间格式
					let year = that.tableEdit.date.getFullYear();
					let month = String(that.tableEdit.date.getMonth() + 1).padStart(2, '0');
					let day = String(that.tableEdit.date.getDate()).padStart(2, '0');
					let dateFormat = year + '-' + month + '-' + day;
					that.tableEdit.date = dateFormat;
				}

				let API = "http://localhost:8088/updateNurse";
				that.$http.post(API, that.tableEdit).then(function() {
					that.dialogFormEditVisible = false;

					if (that.tableEdit.sex == 1) {
						that.tableEdit.sex = "男";
					} else {
						that.tableEdit.sex = "女";
					}
					Vue.set(that.table, that.Index, {
						...that.tableEdit
					});
					that.init();
					this.$message({
						message: '护士信息修改成功',
						type: 'success'
					});
					//console.log('编辑后完成转化格式的日期', that.tableEdit.date);
				}, function() {
					this.$message.error('护士信息修改失败');
				});
			},
			// 删除
			handleDelete(index) {
				let that = this;
				that.processor = sessionStorage.getItem('easeHis');
				this.$prompt('此操作会将让该护士的信息失效, 视为开除, 认真查看后是需要失效的信息, 请填写辞职原因:', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					inputPattern: /.+/,
					inputErrorMessage: '辞职原因不能为空'
				}).then(({
					value
				}) => {
					let API = "http://localhost:8088/deleteNurse";
					let doctorResignInfo = {
						reason: value,
						processor: that.processor,
						id: that.table[index].id
					};
					that.$http.post(API, doctorResignInfo).then((response) => {
						// 从 that.table 数组中移除该项
						that.table.splice(index, 1);
						// 更新总行数
						that.totalNum -= 1;
						that.$message({
							message: '护士信息失效成功',
							type: 'success'
						});
					}).catch((error) => {
						that.$message.error('护士信息失效失败');
					});
				}).catch(() => {
					that.$message({
						type: 'info',
						message: '已取消开除'
					});
				});
			},
			// 搜索
			handelSearch: debounce(function() {
				this.init();
			}, 220), // 220毫秒防抖
			// 显示全部
			getAll() {
				this.searchName = '';
				this.init();
			},
			// 导出
			handleDownload() {
				var vm = this;
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('vendor/Export2Excel');
					const tHeader = ['姓名', '地址', '性别', '年龄', '职称', '科室', '学历', '专业', '入职时间'];
					const filterVal = ['name', 'address', 'sex', 'age', 'position', 'department', 'education',
						'profession',
						'date'
					];
					const table = vm.table;
					const data = vm.formatJson(filterVal, table);
					export_json_to_excel(tHeader, data, '护士信息列表excel');
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			// 点击切换每页显示多少行
			handleSizeChange(val) {
				this.pageSize = val;
				console.log(`每页 ${val} 条`);
				this.init();
			},
			// 点击切换页
			handleCurrentChange(val) {
				this.pageNum = val;
				console.log(`当前页: ${val} `);
				this.init();
			}
		},
		mounted() {
			this.init();
		},
		created() {}
	};
</script>

<style>
	.title p {
		font-size: 24px;
		text-align: center;
		margin-bottom: 50px;
	}

	.nurse_table {
		padding: 10 10px;
		margin-top: 50px;
	}

	.filter-container {
		margin-bottom: 20px;
	}

	.pagination-container {
		margin-top: 50px;
		margin-left: -5px;
	}
</style>